#include <ClanLib/core.h>
#include <ClanLib/application.h>
#include <ClanLib/display.h>
#ifdef USE_SDL
	#include <ClanLib/sdl.h>
#else
	#include <ClanLib/gl.h>
#endif
#include "tileset.h"

Tileset::Tileset()
{
	width = 0; height = 0;
	tile_width = 0; tile_height = 0;
}

Tileset::Tileset(const std::string &resource_id, CL_ResourceManager* manager)
{
	surface = CL_Surface(resource_id, manager);

	CL_Resource resource = manager->get_resource(resource_id);
	resource.load();

	CL_DomElement element = resource.get_element();
	tile_width = CL_String::to_int(element.get_attribute("tile_width"));
	tile_height = CL_String::to_int(element.get_attribute("tile_height"));

	if(tile_width == 0)
		tile_width = 32;
	if(tile_height == 0)
		tile_height = 32;

	resource.unload();

	width = surface.get_width() / tile_width;
	height = surface.get_height() / tile_height;
}

Tileset::~Tileset()
{
}

void Tileset::draw(char &tile, CL_Point &pos, Viewport &viewport)
{
	int top = tile / width;
	int left = tile - (top * width);
	if(left > width)
		left = 0;
	top *= tile_height; left *= tile_width;

	CL_Rect world_area = viewport.get_world_area();
	CL_Rect screen_area = viewport.get_screen_area();
	CL_Rect src( left, top, left + tile_width, top + tile_height );
	CL_Rect dest(pos,src.get_size());
	
	viewport.draw(surface, src, dest);
}

const int &Tileset::get_width(){
	return width;
}

const int &Tileset::get_tile_width(){
	return tile_width;
}

const int &Tileset::get_tile_height(){
	return tile_height;
}